package usersrv

import (
	"github.com/pkg/errors"
	"interview/models"
	"interview/pkg/request"
	"strings"
)

func GetUserList(req request.UserListReq) ([]*models.User, int64, error) {
	filters := make(map[string]interface{})
	if req.Username = strings.TrimSpace(req.Username); req.Username != "" {
		filters["username"] = req.Username
	}
	if req.OpenID = strings.TrimSpace(req.OpenID); req.OpenID != "" {
		filters["openID"] = req.OpenID
	}
	if req.MembershipType != 0 {
		filters["membershipType"] = req.MembershipType
	}

	list, total, err := models.FindUserList(req.PageNum, req.PageSize, filters)
	if err != nil {
		return nil, 0, errors.WithMessage(err, "获取用户列表失败")
	}
	return list, total, nil
}

func AddUser(req request.CreateUserReq) (uint, error) {
	data := make(map[string]interface{})
	data["username"] = req.Username
	data["openID"] = req.OpenID
	data["avatar"] = req.Avatar

	id, err := models.CreateUser(data)
	if err != nil {
		return 0, errors.WithMessage(err, "创建用户失败")
	}
	return id, nil
}
